<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="550px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { message } from "ant-design-vue";
  import { BasicDrawer, useDrawerInner, BasicForm, useForm } from '@gui-pkg/antdcomponents';
  import { formSchema } from './station.data';
  import { addStationData } from '@/api/information/rain';

  const stationId = ref('');
  const isUpdate = ref(true);
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 110,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 22, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      stationId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增测站' : '编辑测站'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      console.log(values);
      // 向后台提交测站数据
      if (unref(isUpdate)) {
        await addStationData({...values, id: unref(stationId)});
        message.success('编辑成功');
      } else {
        await addStationData(values);
        message.success('新增成功');
      }
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" rel="stylesheet/less" scoped>
</style>
